package com.sphd.emanu.activity.choosefood;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sphd.emanu.R;
import com.sphd.emanu.adapter.ChooseTypeAdapter;
import com.sphd.emanu.adapter.ChooseTypeSectionAdapter;
import com.sphd.emanu.adapter.ShoppingCartAdapter;
import com.sphd.emanu.interfaces.FoodNoListener;
import com.sphd.emanu.mvp.MVPBaseActivity;
import com.sphd.emanu.pojo.FoodEntity;
import com.sphd.emanu.pojo.TypeEntity;
import com.sphd.emanu.view.PinnedHeaderListView;
import com.wzutils.L;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 下单界面
 *
 * @Author Hu
 * @Time 2017/4/25 -- 15:22.
 * @Email 87683202@qq.com
 */
public class ChoosefoodActivity extends MVPBaseActivity<ChoosefoodContract.View, ChoosefoodPresenter> implements ChoosefoodContract.View, FoodNoListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.noData)
    TextView noData;
    @BindView(R.id.classify_mainlist)
    ListView classifyMainlist;
    @BindView(R.id.food_mainlist)
    PinnedHeaderListView foodMainlist;
    @BindView(R.id.shopping_cart)
    ImageView shoppingCart;
    @BindView(R.id.shoppingNum)
    TextView shoppingNum;
    @BindView(R.id.shoppingPrise)
    TextView shoppingPrise;
    @BindView(R.id.settlement)
    TextView settlement;
    @BindView(R.id.bottom_toolBar)
    LinearLayout bottomToolBar;
    @BindView(R.id.bg_layout)
    View bgLayout;
    @BindView(R.id.defaultText)
    TextView defaultText;
    @BindView(R.id.shopproductListView)
    ListView shopproductListView;
    @BindView(R.id.cardShopLayout)
    LinearLayout cardShopLayout;
    @BindView(R.id.cardLayout)
    FrameLayout cardLayout;
    @BindView(R.id.parentLayout)
    RelativeLayout parentLayout;

    List<TypeEntity> typeEntityList;
    List<FoodEntity> foodEntityList;
    List<FoodEntity> shopcarList;
    ChooseTypeSectionAdapter chooseTypeSectionAdapter;
    ChooseTypeAdapter chooseTypeAdapter;
    ShoppingCartAdapter shoppingCartAdapter;

    private boolean isScroll = true;//分类是否为滚动状态
    int typePos = -1;
    // 正在执行的动画数量
    private int number = 0;
    // 是否完成清理
    private boolean isClean = false;
    private FrameLayout animation_viewGroup;


    private Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    // 用来清除动画后留下的垃圾
                    try {
                        animation_viewGroup.removeAllViews();
                    } catch (Exception e) {

                    }
                    isClean = false;

                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choosefood);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        chooseTypeSectionAdapter.SetOnSetHolderClickListener(new ChooseTypeSectionAdapter.HolderClickListener() {
            @Override
            public void onHolderClick(Drawable drawable, int[] start_location) {
                doAnim(drawable, start_location);
            }
        });
        /**
         * 对分类list进行点击事件的处理
         */

        classifyMainlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (typePos != position) {
                    typeAdapterItemChanged(true, position);
                    if (typePos != -1) {
                        typeAdapterItemChanged(false, typePos);
                    }
                    typePos = position;

                    int rightSection = 0;
                    for (int i = 0; i < position; i++) {
                        rightSection += chooseTypeSectionAdapter.getCountForSection(i) + 1;
                    }
                    foodMainlist.setSelection(rightSection);
                }
            }
        });
        /**
         *菜品列表的滚动监听
         */

        foodMainlist.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int firstpos = chooseTypeSectionAdapter
                        .getSectionForPosition(firstVisibleItem);
                if (isScroll) {
                    if (typePos != firstpos) {
                        typeAdapterItemChanged(true, firstpos);
                        //对当前的view进行是否可见的判断
                        if (classifyMainlist.getFirstVisiblePosition() > (firstpos - 1) || classifyMainlist.getLastVisiblePosition() < (firstpos + 1)) {
                            classifyMainlist.setSelection(firstpos);
                        }
                        if (typePos != -1) {
                            typeAdapterItemChanged(false, typePos);
                        }
                        typePos = firstpos;
                    }
                } else {
                    isScroll = true;
                }


            }
        });
        chooseTypeSectionAdapter.setFoodNoListener(this);
        shoppingCartAdapter.setFoodNoListener(this);

    }


    private void initView() {
        animation_viewGroup = createAnimLayout();
        setTitleBar(toolbar, "下单");
        getTypeData();
        initTypeAdapter();
        initFoodAdapter();
        initShoppingcatAdapter();

    }

    private void initShoppingcatAdapter() {
        shopcarList = new ArrayList<>();
        shoppingCartAdapter = new ShoppingCartAdapter(context, shopcarList);
        shopproductListView.setAdapter(shoppingCartAdapter);
    }

    private void typeAdapterItemChanged(boolean b, int position) {
        typeEntityList.get(position).setSelected(b);
        chooseTypeAdapter.notifyDataSetChangedItem(classifyMainlist, position);
    }

    /**
     * 初始化分类的list 并对第一条item进行选中处理
     */
    private void initTypeAdapter() {
        chooseTypeAdapter = new ChooseTypeAdapter(context, typeEntityList);
        classifyMainlist.setAdapter(chooseTypeAdapter);

    }

    private void getTypeData() {
        //new 分类对象的list
        typeEntityList = new ArrayList<>();
        for (char c = 'A'; c <= 'Z'; c++) {
            //new 一个分类的对象 进行封装数据
            TypeEntity typeEntity = new TypeEntity();
            typeEntity.setTypeName("分类信息：" + String.valueOf(c));
            //new 菜品的list
            foodEntityList = new ArrayList<>();
            //对菜品的list进行封装数据
            for (int i = 0; i < 10; i++) {
                //新建菜品参数
                FoodEntity foodEntity = new FoodEntity();
                foodEntity.setDishesName("商品：" + String.valueOf(c) + i);
                foodEntity.setType(String.valueOf(c) + i);
                //将菜品添加到菜品List中去
                foodEntityList.add(foodEntity);
            }
            //将封装完毕的菜品list set到分类对象中
            typeEntity.setFoodEntityList(foodEntityList);
            //将分类对象添加到分类的list中去
            typeEntityList.add(typeEntity);
        }
    }

    private void initFoodAdapter() {
        chooseTypeSectionAdapter = new ChooseTypeSectionAdapter(context, typeEntityList);
        foodMainlist.setAdapter(chooseTypeSectionAdapter);

    }



    @Override
    public void add(FoodEntity foodEntity, int type, int pos) {
        //对type进行判断 如果为1则为sectionlist 点击事件
        if (!shopcarList.contains(foodEntity)) {
            shopcarList.add(foodEntity);
        } else {
            if (type == 1) {
                for (FoodEntity foodEntity1 : shopcarList) {
                    //TODO: 2017/4/28  待到正式运行的时候此处替换为id判断
                    if (foodEntity.getType().equals(foodEntity1.getType())) {
                        foodEntity1.setChooseNo(foodEntity.getChooseNo());
                    }
                }
            } else if (type == 2) {
                /**
                 * 思路
                 *  如果此处为购物车的点击事件
                 *  通过购物车adapter传递过来的foodEntity 在typeEntityList 先获取FoodEntityList
                 *  再通过foodEntity.getRepos() 记录的定位获取FoodEntityList 中的实体foodentity
                 *  再进行选购数量的设置
                 */
                typeEntityList.get(foodEntity.getSection()).getFoodEntityList().get(foodEntity.getRepos()).setChooseNo(foodEntity.getChooseNo());

            }
        }
        setPrise();
    }

    @Override
    public void reduce(FoodEntity foodEntity, int type, int pos) {
        if (shopcarList.contains(foodEntity)) {
            if (foodEntity.getChooseNo() == 0) {
                if (type == 2) {
                    shopcarList.remove(foodEntity);
                    adapternotifyDataSetChanged(shoppingCartAdapter);
                    if (shopcarList.size()==0){
                        defaultText.setVisibility(View.VISIBLE);
                    }
                }

            } else {
                if (type == 1) {
                    //// TODO: 2017/4/28 找到sectionadapter 中传递的 entity 在购物车list中对应的实体 将传递过来的entiy中的数量赋值给对应的实体
                    for (FoodEntity foodEntity1 : shopcarList) {
                        if (foodEntity.getType().equals(foodEntity1.getType())) {
                            foodEntity1.setChooseNo(foodEntity.getChooseNo());
                        }
                    }
                } else if (type == 2) {
                    /**
                     * 思路
                     *  如果此处为购物车的点击事件
                     *  通过购物车adapter传递过来的foodEntity 在typeEntityList 先获取FoodEntityList
                     *  再通过foodEntity.getRepos() 记录的定位获取FoodEntityList 中的实体foodentity
                     *  再进行选购数量的设置
                     */
                    typeEntityList.get(foodEntity.getSection()).getFoodEntityList().get(foodEntity.getRepos()).setChooseNo(foodEntity.getChooseNo());

                }

            }
        }
        setPrise();
    }

    private void setPrise() {
        double sum = 0;
        int shopNum = 0;
        for (FoodEntity pro : shopcarList) {
//            sum = sum + (pro.getNumber() * Double.parseDouble(pro.getPrice()))
            shopNum = shopNum + pro.getChooseNo();
        }

        if (shopNum > 0) {
            shoppingNum.setVisibility(View.VISIBLE);
        } else {
            shoppingNum.setVisibility(View.GONE);
        }
        if (sum > 0) {
            shoppingPrise.setVisibility(View.VISIBLE);
        } else {
            shoppingPrise.setVisibility(View.GONE);
        }
        shoppingPrise.setText("¥" + " " + (new DecimalFormat("0.00")).format(sum));
        shoppingNum.setText(String.valueOf(shopNum));
    }


    @OnClick({R.id.shopping_cart, R.id.settlement, R.id.bg_layout, R.id.defaultText})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.shopping_cart:

                if (cardLayout.getVisibility() == View.GONE) {
                    //如果是隐藏的状态那就显示 并刷新购物车
                    cardLayout.setVisibility(View.VISIBLE);
                    // 动画开始
                    cardShopLayout.startAnimation(AnimationUtils.loadAnimation(context, R.anim.push_bottom_in));
                    adapternotifyDataSetChanged(shoppingCartAdapter);
                    if (shopcarList.size() == 0) {
                        defaultText.setVisibility(View.VISIBLE);
                    } else {
                        defaultText.setVisibility(View.GONE);
                    }
                } else {
                    //如果是显示那就隐藏 并刷新section list
                    cardLayout.setVisibility(View.GONE);
                    adapternotifyDataSetChanged(chooseTypeSectionAdapter);
                }
                break;
            case R.id.settlement:

                break;
            case R.id.bg_layout:
                cardLayout.setVisibility(View.GONE);
                adapternotifyDataSetChanged(chooseTypeSectionAdapter);
                break;
            //空白购物车
            case R.id.defaultText:
                cardLayout.setVisibility(View.GONE);
                adapternotifyDataSetChanged(chooseTypeSectionAdapter);
                break;
        }
    }

    private void adapternotifyDataSetChanged(BaseAdapter adapter) {
        adapter.notifyDataSetChanged();
    }

    /**
     * @param
     * @return void
     * @throws
     * @Description: 创建动画层
     */
    private FrameLayout createAnimLayout() {
        ViewGroup rootView = (ViewGroup) getWindow().getDecorView();
        FrameLayout animLayout = new FrameLayout(context);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT);
        animLayout.setLayoutParams(lp);
        animLayout.setBackgroundResource(android.R.color.transparent);
        rootView.addView(animLayout);
        return animLayout;
    }

    private void doAnim(Drawable drawable, int[] start_location) {
        if (!isClean) {
            setAnim(drawable, start_location);
        } else {
            try {
                animation_viewGroup.removeAllViews();
                isClean = false;
                setAnim(drawable, start_location);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                isClean = true;
            }
        }
    }

    /**
     * 动画效果设置
     *
     * @param drawable       将要加入购物车的商品
     * @param start_location 起始位置
     */
    @SuppressLint("NewApi")
    private void setAnim(Drawable drawable, int[] start_location) {
        Animation mScaleAnimation = new ScaleAnimation(1.2f, 0.6f, 1.2f, 0.6f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
        mScaleAnimation.setFillAfter(true);

        final ImageView iview = new ImageView(context);
        iview.setImageDrawable(drawable);
        final View view = addViewToAnimLayout(animation_viewGroup, iview,
                start_location);


        view.setAlpha(0.6f);

        int[] end_location = new int[2];
        settlement.getLocationInWindow(end_location);

        // 计算位移
        int endX = 0 - start_location[0] + 40;// 动画位移的X坐标
        int endY = end_location[1] - start_location[1];// 动画位移的y坐标
        TranslateAnimation translateAnimationX = new TranslateAnimation(0,
                endX, 0, 0);
        translateAnimationX.setInterpolator(new LinearInterpolator());
        translateAnimationX.setRepeatCount(0);// 动画重复执行的次数
        translateAnimationX.setFillAfter(true);

        TranslateAnimation translateAnimationY = new TranslateAnimation(0, 0,
                0, endY);
        translateAnimationY.setInterpolator(new AccelerateInterpolator());
        translateAnimationY.setRepeatCount(0);// 动画重复执行的次数
        translateAnimationX.setFillAfter(true);


        Animation mRotateAnimation = new RotateAnimation(0, 180,
                Animation.RELATIVE_TO_SELF, 0.3f, Animation.RELATIVE_TO_SELF,
                0.3f);
        mRotateAnimation.setFillAfter(true);

        AnimationSet set = new AnimationSet(false);
        set.setFillAfter(false);
        set.addAnimation(mRotateAnimation);
        set.addAnimation(mScaleAnimation);
        set.addAnimation(translateAnimationY);
        set.addAnimation(translateAnimationX);
        set.setDuration(500);// 动画的执行时间
        view.startAnimation(set);
        set.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                number++;
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                number--;
                if (number == 0) {
                    isClean = true;
                    myHandler.sendEmptyMessage(0);
                }

                ObjectAnimator.ofFloat(shoppingCart, "translationY", 0, 4, -2, 0).setDuration(400).start();
                ObjectAnimator.ofFloat(shoppingNum, "translationY", 0, 4, -2, 0).setDuration(400).start();

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

        });

    }

    /**
     * @param vg       动画运行的层 这里是frameLayout
     * @param view     要运行动画的View
     * @param location 动画的起始位置
     * @return
     * @deprecated 将要执行动画的view 添加到动画层
     */
    private View addViewToAnimLayout(ViewGroup vg, View view, int[] location) {
        int x = location[0];
        int y = location[1];
        vg.addView(view);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = x;
        lp.topMargin = y;
        view.setPadding(5, 5, 5, 5);
        view.setLayoutParams(lp);

        return view;
    }

    /**
     * 内存过低时及时处理动画产生的未处理冗余
     */
    @Override
    public void onLowMemory() {
        isClean = true;
        try {
            animation_viewGroup.removeAllViews();
        } catch (Exception e) {
            e.printStackTrace();
        }
        isClean = false;
        super.onLowMemory();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
